<template>
  <MainLayout>
    <div class="home-content">
      <!-- Banner轮播图 -->
      <el-carousel :interval="4000" type="card" height="400px" class="home-banner">
        <el-carousel-item v-for="item in bannerImages" :key="item.id">
          <img :src="item.url" class="banner-image" @click="handleBannerClick(item)" />
        </el-carousel-item>
      </el-carousel>

      <!-- 分类导航 -->
      <el-row :gutter="20" style="margin-top: 30px">
        <el-col :span="6" v-for="category in categories" :key="category.name">
          <el-card 
            :body-style="{ padding: '20px', textAlign: 'center' }" 
            shadow="hover" 
            class="category-card"
            @click="goToCategory(category.key)"
          >
            <div class="category-icon">{{ category.icon }}</div>
            <h3>{{ category.name }}</h3>
          </el-card>
        </el-col>
      </el-row>

      <!-- 热门商品 -->
      <el-divider><span style="font-size: 18px;">🔥 热门商品</span></el-divider>
      <el-row :gutter="20">
        <el-col :span="6" v-for="product in hotProducts" :key="product.id">
          <el-card 
            :body-style="{ padding: '0' }" 
            shadow="hover" 
            class="product-card" 
            @click="goToProduct(product.id)"
          >
            <img :src="product.image" class="product-image" />
            <div style="padding: 14px;">
              <h4>{{ product.name }}</h4>
              <p class="product-price">¥{{ product.price }}</p>
              <el-button type="primary" size="small" @click.stop="addToCart(product)">
                加入购物车
              </el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </MainLayout>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import MainLayout from '../layouts/MainLayout.vue'

const router = useRouter()

const bannerImages = ref([
  {
    id: 1,
    url: 'https://images.unsplash.com/photo-1441986300917-64674bd600d8?w=1200',
    title: '春季新品上市',
    link: '/category/clothing'
  },
  {
    id: 2,
    url: 'https://images.unsplash.com/photo-1555529669-2269763671c0?w=1200',
    title: '数码产品大促销',
    link: '/category/digital'
  },
  {
    id: 3,
    url: 'https://images.unsplash.com/photo-1607082349566-187342175e2f?w=1200',
    title: '精选美妆',
    link: '/category/makeup'
  },
  {
    id: 4,
    url: 'https://images.unsplash.com/photo-1563729784474-d77dbb933a9e?w=1200',
    title: '新鲜生鲜直达',
    link: '/category/fresh'
  }
])

const categories = ref([
  { name: '美妆', key: 'makeup', icon: '💄' },
  { name: '服饰', key: 'clothing', icon: '👗' },
  { name: '数码', key: 'digital', icon: '📱' },
  { name: '电器', key: 'appliance', icon: '🔌' },
  { name: '生鲜', key: 'fresh', icon: '🍎' },
  { name: '户外', key: 'outdoor', icon: '🏕️' }
])
const hotProducts = ref([])

const fetchHotProducts = async () => {
  try {
    const response = await axios.get('http://localhost:3000/api/products/hot')
    hotProducts.value = response.data
  } catch (error) {
    console.error('获取热门商品失败:', error)
    // 使用模拟数据
    hotProducts.value = [
      { id: 1, name: '保湿面膜', price: 89, image: 'https://picsum.photos/200?random=1', category: 'makeup' },
      { id: 4, name: '春季连衣裙', price: 299, image: 'https://picsum.photos/200?random=4', category: 'clothing' },
      { id: 7, name: '蓝牙耳机', price: 399, image: 'https://picsum.photos/200?random=7', category: 'digital' },
      { id: 10, name: '电饭煲', price: 299, image: 'https://picsum.photos/200?random=10', category: 'appliance' }
    ]
  }
}

const goToCategory = (category) => {
  router.push(`/category/${category}`)
}

const goToProduct = (id) => {
  router.push(`/product/${id}`)
}

const addToCart = (product) => {
  const savedCart = localStorage.getItem('cart')
  let cartItems = savedCart ? JSON.parse(savedCart) : []
  
  // 检查是否已存在
  const existingItem = cartItems.find(item => item.id === product.id)
  if (existingItem) {
    existingItem.quantity += 1
  } else {
    cartItems.push({ ...product, quantity: 1 })
  }
  
  localStorage.setItem('cart', JSON.stringify(cartItems))
  ElMessage.success('已添加到购物车')
}

const handleBannerClick = (item) => {
  router.push(item.link)
}

onMounted(() => {
  fetchHotProducts()
})
</script>

<style scoped>
.home-content {
  width: 100%;
  max-width: 100%;
  padding: 0;
  box-sizing: border-box;
}

.home-banner {
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.banner-image {
  width: 100%;
  height: 400px;
  object-fit: cover;
  cursor: pointer;
  transition: transform 0.3s;
}

.banner-image:hover {
  transform: scale(1.05);
}

.category-card {
  cursor: pointer;
  transition: all 0.3s;
}

.category-card:hover {
  transform: translateY(-5px);
}

.category-icon {
  font-size: 48px;
  margin-bottom: 10px;
}

.product-card {
  cursor: pointer;
  transition: all 0.3s;
  margin-bottom: 20px;
}

.product-card:hover {
  transform: translateY(-5px);
}

.product-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.product-price {
  color: #f56c6c;
  font-size: 18px;
  font-weight: bold;
  margin: 10px 0;
}
</style>

